package com.tang.model.template.jdbc;

import com.tang.model.template.jdbc.util.ConnectionPool;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * @Author tangyuan2meicloud.com
 * @DATE 2021/8/31 22:31
 * @Desc
 * @Remarks
 */
public abstract class JDBCTemplate<T> {

    public List<T> execQuery(String sql, RowMapper<T> rowMapper, Object[] params) {
        try {
//        获取连接
            Connection connection = ConnectionPool.getConnection();
//        构建PrepareStatement
            PreparedStatement preparedStatement = createPrepareStatement(connection, sql, params);
//        执行SQL 获取ResultSet
            ResultSet resultSet = preparedStatement.executeQuery();
//        调用方法去将ResultSet转换为对象
            List<T> result = transfer2Object(resultSet, rowMapper);
//        关闭资源
            resultSet.close();
            preparedStatement.close();
            ConnectionPool.release(connection);
//        返回结果集
            return result;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
        }
        return null;
    }

    private List<T> transfer2Object(ResultSet resultSet, RowMapper<T> rowMapper) throws SQLException {
        List<T> result = new ArrayList<>();
        int row = 1;
        while (resultSet.next()) {
            result.add(rowMapper.mapRow(resultSet, row++));
        }
        return result;
    }

    private PreparedStatement createPrepareStatement(Connection connection, String sql, Object[] params) throws SQLException {
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        if (null == params || params.length < 1) {
            return preparedStatement;
        }
        for (int i = 0; i < params.length; i++) {
            preparedStatement.setObject(i, params[i]);
        }
        return preparedStatement;
    }

}
